﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using System.Data;
using ZEBuz.Questionnaire.Lib.Util;
using ZEBuz.Questionnaire.Lib.Core;

namespace ZEBuz.Questionnaire.Lib.Entities
{
    public class User
    {
        public string UserId { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
        public int MarriageAge { get; set; }
        public string Password { get; set; }
        public string SecurityQuestion { get; set; }
        public string SecurityAnswer { get; set; }
        public string Mobile { get; set; }
        public bool HasChild { get; set; }

        public User()
        {
            this.Name = string.Empty;
            this.Sex = "U";
            this.Email = string.Empty;
            this.Age = -1;
            this.MarriageAge = -1;
            this.Password = string.Empty;
            this.SecurityQuestion = string.Empty;
            this.SecurityAnswer = string.Empty;
            this.Mobile = string.Empty;
        }

        public void Logon(User user)
        {
            if (System.Web.HttpContext.Current.Session["User"] == null)
                System.Web.HttpContext.Current.Session.Add("User", user);
            else
                System.Web.HttpContext.Current.Session["User"] = user;
        }

        public string GetLogonUserId()
        {
            if (IsLogged)
            {
                return System.Web.HttpContext.Current.Session["User"].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public bool IsLogged
        {
            get
            {
                return !string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["User"] == null ? string.Empty : System.Web.HttpContext.Current.Session["User"].ToString());
            }
        }

        public User Get(string userId)
        {
            string sql = string.Empty;
            using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                try
                {
                    DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, "select * from users where userid='" + userId + "'");
                    if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
                    {
                        return null;
                    }
                    DataRow dr = ds.Tables[0].Rows[0];
                    return new User
                    {
                        UserId = UserId,
                        Name = dr["name"].ToString(),
                        Sex = dr["sex"].ToString(),
                        Email = dr["sex"].ToString(),
                        Age = dr["Age"].ToString().ToInt(-1),
                        MarriageAge = dr["MarriageAge"].ToString().ToInt(-1),
                        Password = dr["Password"].ToString(),
                        SecurityAnswer = dr["SecurityAnswer"].ToString(),
                        SecurityQuestion = dr["SecurityQuestion"].ToString(),
                        Mobile = dr["Mobile"].ToString()
                    };
                }
                catch (Exception ex)
                {
                    LogHelper.Log("UserCreate", sql, ex.Message, ex.InnerException != null ? ex.InnerException.Message : string.Empty);
                    throw ex;
                }


            }
        }

        private User getFromDatareader(DataRow dr)
        {
            return new User
            {
                UserId = dr["userid"].ToString(),
                Name = dr["name"].ToString(),
                Sex = dr["sex"].ToString(),
                Email = dr["email"].ToString(),
                Age = dr["Age"].ToString().ToInt(-1),
                MarriageAge = dr["MarriageAge"].ToString().ToInt(-1),
                Password = dr["Password"].ToString(),
                SecurityAnswer = dr["SecurityAnswer"].ToString(),
                SecurityQuestion = dr["SecurityQuestion"].ToString(),
                Mobile = dr["Mobile"].ToString()
            };
        }

        public static bool HasMobileForSignup(string mobile)
        {
            string sql = string.Empty;
            using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                try
                {
                    DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text,
                        "select * from users where mobile = '" + mobile + "'");
                    if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
                    {
                        return false;
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public static bool HasEmailForSignup(string email)
        {
            string sql = string.Empty;
            using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                try
                {
                    DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text,
                        "select * from users where email = '" + email + "'");
                    if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
                    {
                        return false;
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public User Get(string email, string pwd)
        {
            string sql = string.Empty;
            using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                try
                {
                    DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text,
                        "select * from users where email = '" + email + "' and password='" + pwd + "'");
                    if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
                    {
                        return null;
                    }
                    return getFromDatareader(ds.Tables[0].Rows[0]);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public void Add()
        {
            string sql = string.Empty;
            using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                try
                {
                    sql = string.Format("insert into users (userid,name,sex,email,age,marriageAge,password,mobile) " +
                       "values ('{0}','{1}','{2}','{3}',{4},{5},'{6}','{7}')",
                       this.UserId, this.Name, this.Sex, this.Email, this.Age, this.MarriageAge, this.Password, this.Mobile);

                    SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);


                    //List<SqlParameter> paras = new List<SqlParameter>();
                    //SqlParameter[] p = 
                    //{
                    //    new SqlParameter("p_UserId", this.UserId),
                    //    new SqlParameter("p_Name", this.Name),
                    //    new SqlParameter("p_Sex", this.Sex),
                    //    new SqlParameter("p_Email", this.Email),
                    //    new SqlParameter("p_Age", this.Age),
                    //    new SqlParameter("p_MarriageAge", this.MarriageAge),
                    //    new SqlParameter("p_Password", this.Password),
                    //    new SqlParameter("p_SecurityQuestion", this.SecurityQuestion),
                    //    new SqlParameter("p_SecurityAnswer", this.SecurityAnswer),
                    //    new SqlParameter("p_Mobile", this.Mobile)
                    //};
                    //object o = SqlHelper.ExecuteScalar(
                    //    conn,
                    //    CommandType.StoredProcedure,
                    //    "usp_Insert_User", p);

                    //if (o == null)
                    //{
                    //    throw new Exception("奇怪..");

                    //}
                    //int ret = o.ToString().ToInt();

                    //if (ret == 0)
                    //    throw new Exception("请至少提供手机号或邮箱");
                    //if (ret == -1)
                    //    throw new Exception("手机号或邮箱已存在");

                }
                catch (Exception ex)
                {
                    LogHelper.Log("MethodCreateUser", sql, ex.Message, ex.InnerException != null ? ex.InnerException.Message : string.Empty);
                    throw ex;
                }
            }
        }
    }
}
